﻿using ezCloud.Api.Common;
using ezCloud.Data;
using Microsoft.AspNet.Identity;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Script.Serialization;

namespace ezCloud.Api.Controllers
{
    [RoutePrefix("api/Business")]
    public class BusinessController : ezController
    {
        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("AddNewCompany")]
        public async Task<IHttpActionResult> AddNewCompany(Company model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            var user = UserUtitily.getUserProfile();
            model.IsAvailable = true;
            model.CreatedDate = DateTime.UtcNow;
            model.CreatedUserId = user.UserId;
            model.HotelId = user.HotelId;
            model.SourceId = model.SourceId == 0 ? null : model.SourceId;
            context.Company.InsertOnSubmit(model);
            context.SubmitChanges();
            Elastic.IndexLastAudit(context);
            return Ok();
        }

        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("AddNewMarket")]
        public async Task<IHttpActionResult> AddNewMarket(Market model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            var user = UserUtitily.getUserProfile();
            model.IsAvailable = true;
            model.CreatedDate = DateTime.UtcNow;
            model.CreatedUserId = user.UserId;
            model.HotelId = user.HotelId;

            context.Market.InsertOnSubmit(model);
            context.SubmitChanges();
            Elastic.IndexLastAudit(context);
            return Ok();
        }

        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("AddNewSource")]
        public async Task<IHttpActionResult> AddNewSource(Source model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            var user = UserUtitily.getUserProfile();
            model.IsAvailable = true;
            model.CreatedDate = DateTime.UtcNow;
            model.CreatedUserId = user.UserId;
            model.HotelId = user.HotelId;
            context.Source.InsertOnSubmit(model);
            context.SubmitChanges();
            Elastic.IndexLastAudit(context);
            return Ok();
        }

        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("ChangeCompanyStatus")]
        public async Task<IHttpActionResult> ChangeCompanyStatus(int companyId)
        {
            var user = UserUtitily.getUserProfile();
            /*
            if (
                context.Reservations.Any(res => res.HotelId == user.HotelId && res.CompanyId == companyId))
            {
                return BadRequest("CANNOT_CHANGE_STATUS_BECAUSE_THIS_COMPANY_IS_SELECTED_IN_SOME_RESERVATIONS");
            }*/
            var oldCompany =
                context.Company.FirstOrDefault(src => src.HotelId == user.HotelId && src.CompanyId == companyId);
            if (oldCompany == null)
            {
                return BadRequest("COMPANY_DOES_NOT_EXIST");
            }
            oldCompany.IsAvailable = !oldCompany.IsAvailable;
            context.SubmitChanges();
            Elastic.IndexLastAudit(context);
            return Ok();
        }

        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("ChangeMarketListPriority")]
        public async Task<IHttpActionResult> ChangeMarketListPriority(List<Market> model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            var user = UserUtitily.getUserProfile();
            var oldMarketList = context.Market.Where(src => src.HotelId == user.HotelId).ToList();
            foreach (var oldMarket in oldMarketList)
            {
                var market =
                    model.FirstOrDefault(src => src.MarketId == oldMarket.MarketId && src.HotelId == user.HotelId);
                if (market != null)
                {
                    oldMarket.Priority = market.Priority;
                }
            }
            context.SubmitChanges();
            Elastic.IndexLastAudit(context);
            return Ok();
        }

        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("ChangeMarketStatus")]
        public async Task<IHttpActionResult> ChangeMarketStatus(int marketId)
        {
            var user = UserUtitily.getUserProfile();
            /*
            if (
                context.Reservations.Any(res => res.HotelId == user.HotelId && res.MarketId == marketId))
            {
                return BadRequest("CANNOT_CHANGE_STATUS_BECAUSE_THIS_MARKET_IS_SELECTED_IN_SOME_RESERVATIONS");
            }*/

            var oldMarket =
                context.Market.FirstOrDefault(src => src.HotelId == user.HotelId && src.MarketId == marketId);
            if (oldMarket == null)
            {
                return BadRequest("SOURCE_DOES_NOT_EXIST");
            }
            oldMarket.IsAvailable = !oldMarket.IsAvailable;
            context.SubmitChanges();
            Elastic.IndexLastAudit(context);
            return Ok();
        }

        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("ChangeSourceListPriority")]
        public async Task<IHttpActionResult> ChangeSourceListPriority(List<Source> model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            var user = UserUtitily.getUserProfile();
            var oldSourceList = context.Source.Where(src => src.HotelId == user.HotelId).ToList();
            foreach (var oldSource in oldSourceList)
            {
                var source =
                    model.FirstOrDefault(src => src.SourceId == oldSource.SourceId && src.HotelId == user.HotelId);
                if (source != null)
                {
                    oldSource.Priority = source.Priority;
                }
            }
            context.SubmitChanges();
            Elastic.IndexLastAudit(context);
            return Ok();
        }

        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("ChangeSourceStatus")]
        public async Task<IHttpActionResult> ChangeSourceStatus(int sourceId)
        {
            var user = UserUtitily.getUserProfile();
            /*
            if (context.Reservations.Any(res => res.HotelId == user.HotelId && res.SourceId == sourceId))
            {
                return BadRequest("CANNOT_CHANGE_STATUS_BECAUSE_THIS_SOURCE_IS_SELECTED_IN_SOME_RESERVATIONS");
            }
            if (context.Company.Any(res => res.HotelId == user.HotelId && res.SourceId == sourceId))
            {
                return BadRequest("CANNOT_CHANGE_STATUS_BECAUSE_THIS_SOURCE_IS_SELECTED_IN_SOME_COMPANIES");
            }*/

            var oldSource = context.Source.FirstOrDefault(src => src.HotelId == user.HotelId && src.SourceId == sourceId);
            if (oldSource == null)
            {
                return BadRequest("SOURCE_DOES_NOT_EXIST");
            }
            oldSource.IsAvailable = !oldSource.IsAvailable;
            context.SubmitChanges();
            Elastic.IndexLastAudit(context);
            return Ok();
        }

        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("EditCompany")]
        public async Task<IHttpActionResult> EditCompany(Company model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            var user = UserUtitily.getUserProfile();
            var oldCompany =
                context.Company.FirstOrDefault(src => src.HotelId == user.HotelId && src.CompanyId == model.CompanyId);
            if (oldCompany == null)
            {
                return BadRequest("COMPANY_DOES_NOT_EXIST");
            }
            oldCompany.CompanyName = model.CompanyName;
            oldCompany.SourceId = model.SourceId == 0 ? null : model.SourceId;
            oldCompany.Description = model.Description;
            oldCompany.CompanyMobile = model.CompanyMobile;
            oldCompany.CompanyPhone = model.CompanyPhone;
            oldCompany.CompanyEmail = model.CompanyEmail;
            oldCompany.CompanyFax = model.CompanyFax;
            oldCompany.ModifiedDate = DateTime.UtcNow;
            oldCompany.ModifiedUserId = user.UserId;
            oldCompany.ContactName = model.ContactName;
            oldCompany.ContactAddress = model.ContactAddress;
            oldCompany.ContactEmail = model.ContactEmail;
            oldCompany.ContactMobile = model.ContactMobile;
            oldCompany.ContactPosition = model.ContactPosition;
            context.SubmitChanges();
            Elastic.IndexLastAudit(context);
            return Ok();
        }

        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("EditMarket")]
        public async Task<IHttpActionResult> EditMarket(Market model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            var user = UserUtitily.getUserProfile();
            var oldMarket =
                context.Market.FirstOrDefault(src => src.HotelId == user.HotelId && src.MarketId == model.MarketId);
            if (oldMarket == null)
            {
                return BadRequest("MARKET_DOES_NOT_EXIST");
            }
            oldMarket.MarketName = model.MarketName;
            oldMarket.ModifiedDate = DateTime.UtcNow;
            oldMarket.ModifiedUserId = user.UserId;
            context.SubmitChanges();
            Elastic.IndexLastAudit(context);
            return Ok();
        }

        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("EditSource")]
        public async Task<IHttpActionResult> EditSource(Source model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var user = UserUtitily.getUserProfile();
            var oldSource = context.Source.FirstOrDefault(src => src.HotelId == user.HotelId && src.SourceId == model.SourceId);
            if (oldSource == null)
            {
                return BadRequest("SOURCE_DOES_NOT_EXIST");
            }
            //test

            oldSource.SourceName = model.SourceName;
            oldSource.Color = model.Color;
            oldSource.RegistrationNumber = model.RegistrationNumber;
            oldSource.ModifiedDate = DateTime.UtcNow;
            oldSource.ModifiedUserId = user.UserId;
            context.SubmitChanges();
            Elastic.IndexLastAudit(context);
            return Ok();
        }

        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("GetAllBusinessData")]
        public async Task<IHttpActionResult> GetAllBusinessData()
        {
            var user = UserUtitily.getUserProfile();
            var sourceList = context.Source.Where(src => src.HotelId == user.HotelId).ToList();
            var companyList = context.Company.Where(com => com.HotelId == user.HotelId).ToList();
            var marketList = context.Market.Where(mar => mar.HotelId == user.HotelId).ToList();
            return Ok(new
            {
                sourceList,
                companyList,
                marketList
            });
        }

        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("GetAllSources")]
        public async Task<IHttpActionResult> GetAllSources()
        {
            var user = UserUtitily.getUserProfile();
            return Ok(context.Source.Where(src => src.HotelId == user.HotelId).ToList());
        }
        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("RemoveBusiness")]
        public async Task<IHttpActionResult> RemoveBusiness(object model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            var user = UserUtitily.getUserProfile();
            var type = model.GetType();
            if (((JObject)model).Property("CompanyCode") != null)
            {
                var jss = new JavaScriptSerializer();
                var oldCompany = jss.Deserialize<Company>(model.ToString());
                if (
                    context.Reservations.Any(res => res.HotelId == user.HotelId && res.CompanyId == oldCompany.CompanyId)
                    || 
                    context.Payments.Any(p=>p.HotelId==user.HotelId && p.CompanyId==oldCompany.CompanyId)
                    )
                {
                    return BadRequest("CANNOT_DELETE_BECAUSE_THIS_COMPANY_IS_SELECTED_IN_SOME_RESERVATIONS");
                }
                var deleteCompany =
                    context.Company.FirstOrDefault(
                com => com.HotelId == user.HotelId && com.CompanyId == oldCompany.CompanyId);
                if (deleteCompany != null)
                {
                    context.Company.DeleteOnSubmit(deleteCompany);
                }
                context.SubmitChanges();
                Elastic.IndexLastAudit(context);
            }

            if (((JObject)model).Property("ShortCode") != null)
            {
                var jss = new JavaScriptSerializer();
                var oldSource = jss.Deserialize<Source>(model.ToString());
                if (
                    context.Reservations.Any(res => res.HotelId == user.HotelId && res.SourceId == oldSource.SourceId))
                {
                    return BadRequest("CANNOT_DELETE_BECAUSE_THIS_SOURCE_IS_SELECTED_IN_SOME_RESERVATIONS");
                }
                if (
                    context.Company.Any(res => res.HotelId == user.HotelId && res.SourceId == oldSource.SourceId))
                    return BadRequest("CANNOT_DELETE_BECAUSE_THIS_SOURCE_IS_SELECTED_IN_SOME_COMPANIES");
                var deleteSource =
                    context.Source.FirstOrDefault(
                com => com.HotelId == user.HotelId && com.SourceId == oldSource.SourceId);
                if (deleteSource != null)
                {
                    context.Source.DeleteOnSubmit(deleteSource);
                }
                context.SubmitChanges();
                Elastic.IndexLastAudit(context);
            }

            if (((JObject)model).Property("MarketCode") != null)
            {
                var jss = new JavaScriptSerializer();
                var oldMarket = jss.Deserialize<Market>(model.ToString());
                if (
                    context.Reservations.Any(res => res.HotelId == user.HotelId && res.MarketId == oldMarket.MarketId))
                {
                    return BadRequest("CANNOT_DELETE_BECAUSE_THIS_MARKET_IS_SELECTED_IN_SOME_RESERVATIONS");
                }
                var deleteMarket =
                    context.Market.FirstOrDefault(
                com => com.HotelId == user.HotelId && com.MarketId == oldMarket.MarketId);
                if (deleteMarket != null)
                {
                    context.Market.DeleteOnSubmit(deleteMarket);
                }
                context.SubmitChanges();
                Elastic.IndexLastAudit(context);
            }

            return Ok();
        }

        [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
        [Route("RemoveSource")]
        public async Task<IHttpActionResult> RemoveSource(Source model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            var user = UserUtitily.getUserProfile();
            var oldSource =
                context.Source.FirstOrDefault(src => src.HotelId == user.HotelId && src.SourceId == model.SourceId);
            if (oldSource == null)
            {
                return BadRequest("SOURCE_DOES_NOT_EXIST");
            }
            context.Source.DeleteOnSubmit(oldSource);
            context.SubmitChanges();
            Elastic.IndexLastAudit(context);
            return Ok();
        }
    }
}